// subPages/mine/myOrders/myOrders.js
const app = getApp()
var util =  require('../../../utils/util.js');
var loadMoreView,p = 1,num = app.globalData.pageNum,type = 'orders',isChange = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mainNavList: [{nav: '社区商城'},{nav: '健康商城'},{nav:'特膳厨房'}],
    navList: [{nav: '全部',isShow: true},{nav: '待付款',isShow: true},{nav: '待发货',isShow: true},{nav: '待收货',isShow: true},{nav: '已完成',isShow: true},{nav: '已评价',isShow: false}],
    current: 0,
    status: 10,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    if(options.type){
      that.setData({
        mainCurrent: options.type,
      })
    }else{
      that.setData({
        mainCurrent: 0
      })
    }
    that.setMainNav(that.data.mainCurrent)

  },

  //选择主导航栏
  switchMainNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;
    if (that.data.mainCurrent == cur) {
      return false;
    } else {
      var navList = that.data.navList
      for(var i in navList){
        if(navList[i].nav == '已评价'){
          navList[i].isShow = cur!=1?false:true
        }
      }
      that.setMainNav(cur)
      that.setData({
        mainCurrent: cur,
        navList: navList
      })
      p = 1
      isChange = true;
      that.getData()
    }
  },

  //设置主导航
  setMainNav:function(cur){
    var typeUrl = ''
    var operationUrl = ''
    switch (cur) {
      case 0:
        typeUrl = '/get_user_community_service_shop_product_order'
        break;
      case 1:
        typeUrl = '/get_user_community_shop_product_order'
        break;
      case 2:
        typeUrl = '/user_get_service_kitchen_order'
    }
    this.setData({
      typeUrl: typeUrl,
      operationUrl: operationUrl,
    })
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;
    if (that.data.current == cur) {
      return false;
    } else {
      that.setData({
        current: cur
      })
      that.setNav(that.data.current)
    }
  },

  //设置导航
  setNav:function(current){
    var status = ''
    switch (current) {
      case 0:
        status = 10
        break;
      case 1:
        status = 0
        break;
      case 2:
        status = 1
        break;
      case 3:
        status = 2
        break;
      case 4:
        status = 3
        break;
      case 5:
        status = 4
        break;
    }
    this.setData({
      status: status
    })
    isChange = true
    this.getData()
  },

  //获取数据
  getData:function(){
    //获取商品数据
    console.log(this.data.typeUrl)
    util.getAjax(app.globalData.apiUrl + `${this.data.typeUrl}`,this.getOrderData,{user_id: this.data.userId,status: this.data.status,p: p,num: num},this.getDataErr)
  },

  getOrderData(res){
    var that = this
    console.log(res)
    if(res.data.list.length != 0){
      var list = []
      if(p == 1) {
        list = res.data.list
      } else {
        list = that.data.orderList.concat(res.data.list)
      }
      for(let i in list){
        list[i].statusTxt = util.getOrderStatus(list[i].status);
        list[i].order_time = util.setTime2(list[i].timestamp)
      }
      that.setData({
        isOrderList: true,
        orderList: list
      })
        console.log(list);
        //商品列表获取到数据进行遍历
      for(let i in that.data.orderList){
        if(that.data.orderList[i].status == 0 && that.data.orderList[i].closetime){
          isChange = false
          that.countdown(that,that.data.orderList[i].closetime,i)
        }
      }
    }else{
      that.setData({
        isOrderList:false,
        orderList: []
      })
    }
    loadMoreView = that.selectComponent("#loadMoreView")
    loadMoreView.loadMoreComplete(res.data,type)
  },

  // 适用于商品列表倒计时
  countdown:function(that,end_time,i){
    if(isChange){
      return
    }

    var list = that.data.orderList
    if(!list[i])return
    if(list[i].isEnd)return
    var endTime = new Date(String(util.setTime2(end_time)).replace(/-/g,"/")).getTime() || [];//倒计时的结束时间
    var nowTime = new Date().getTime();//当前时间
    var total_micro_second = endTime - nowTime || []
    // console.log(total_micro_second);
    if (total_micro_second <= 0) {
      list[i].isEnd = true
    }
    // 渲染倒计时时钟
    var count = util.dateformat(total_micro_second)//剩余的微秒
    var countList = []
    for(var j=0;j<count.length;j++){
      countList.push(count.charAt(j))
    }
    list[i].countList = countList

      // console.log(list);
      that.setData({
      orderList: list
    })
    setTimeout(function () {
      that.countdown(that,end_time,i);
    }, 1000)
  },

  //获取商品数据异常
  getDataErr(err){
    if(p>1){
      loadMoreView.loadMoreFail()
    }else{
      util.showModal('提示','获取订单失败，请向上滑动屏幕')
      this.setData({
        isFail: true
      })
    }
  },

  loadMoreListener: function(e) {
    p += 1
    this.getData()
  },

  clickLoadMore: function(e) {
    this.getData()
  },

  //订单详情
  orderDetails:function(e){
    var that = this;
    var isEnd = e.currentTarget.dataset.isend
    if(isEnd){
      util.showToast('支付时间已截止','none',1000)
      return
    }
    wx.navigateTo({
      url: '../orderDetails/orderDetails?orderclass='+that.data.mainCurrent+'&orderNum=' + e.currentTarget.dataset.ordernum,
    })
  },

  //操作按钮
  operationBtn:function(e){
    var id = e.currentTarget.dataset.id
    var type = e.currentTarget.dataset.type
    var that = this
    switch (type) {
      case '1':
        //确认收货
        util.getAjax(app.globalData.apiUrl + '/health_shop_user_yes_order',function(res){
          // console.log(res)
          if(res.data == 1){
            util.showToast(e.currentTarget.dataset.text + '成功','success',1000)
            that.getData()
          }else{
            util.showToast(e.currentTarget.dataset.text + '失败，请重新点击','none',1000)
          }
        },{order_id: e.currentTarget.dataset.id})
        break;

      case '2':
        //删除订单
        util.showModelAll('提示','是否删除该订单',function(){
          util.getAjax(app.globalData.apiUrl + '/operation_user_community_shop_product_order',function(res){
            // console.log(res)
            if(res.data == 1){
              util.showToast(e.currentTarget.dataset.text + '成功','success',1000)
              that.getData()
            }else{
              util.showToast(e.currentTarget.dataset.text + '失败，请重新点击','none',1000)
            }
          },{id: e.currentTarget.dataset.id,type: e.currentTarget.dataset.type})
        })
        break;
    }

  },

  //查看商品详情
  // shopDetails:function(e){
  //   wx.navigateTo({
  //     url: '/subPages/health/healthShopDetails/healthShopDetails?id=' + e.currentTarget.dataset.id
  //   })
  // },

  //评价按钮
  evaluationBtn:function(e){
    wx.navigateTo({
      url: '/subPages/health/evaluation/evaluation?id=' + e.currentTarget.dataset.id
    })
  },
  
  //获取formid
  // getFormId(e){
  //   let that = this;
  //   let formId = e.detail.formId;
  //     console.log(formId);
  //   that.setData({
  //       formId:formId
  //   })
  // },
  //提醒发货
  remind:function(e){
    util.showToast('已提醒卖家发货','none',2000);
    return; 
    //   util.getAjax(`${app.globalData.apiUrl}/user_tx_fh`,res=>{
    //     console.log(res);
    //     if(res==1){
    //       util.showToast('已提醒卖家发货','none',2000);
    //     }
    // },{
    //   type:type,
    //   order_id:order_id,
    //   form_id:formId
    // })
  },

  //回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 600) {
      this.setData({
        isTop: true
      });
    } else {
      this.setData({
        isTop: false
      });
    }
  },
  //删除订单（厨房，商城）
  delOrder(e){
    var type = e.currentTarget.dataset.del_type;
    var order_id = e.currentTarget.dataset.id;
    let that = this;
    wx.showModal({
        title:'提示',
        content:'是否删除该订单',
        success(res){
          if(res.confirm){
              util.getAjax(`${app.globalData.apiUrl}/user_delete_order`,res=>{
                  console.log(res);
                  if(res.data == 1){
                      util.showToast('订单已删除','success',1000)
                      that.getData()
                  }
              },{
                  type:type,
                  order_id:order_id
              })
          }
        }
    })

  },
  //商城去人收货
  shopConfirmReceive:function(e){
    let order_id = e.currentTarget.dataset.order_id;
    let that = this;
    util.getAjax(`${app.globalData.apiUrl}/user_yes_service_shop_order`,res=>{
        console.log(res);
        if(res.data == 1){
          util.showToast('确认已收货','success',1000);
          that.getData();
        }
    },{
      order_id:order_id
    })
  },

  //特膳厨房确认收货
  kitchenConfirmReceive:function(e){
    var order_id = e.currentTarget.dataset.order_id;
    var that = this;
    util.getAjax(`${app.globalData.apiUrl}/user_yes_kitchen_order`,(res)=>{
        // console.log(res);
        if(res.data == 1){
          util.showToast('确认收货','success',1000);
          that.getData();
        }
    },{
      order_id:order_id
    })
  },

  //社区商城确认收货
  confirmShopBtn:function(e){
      var order_id = e.currentTarget.dataset.id;
      console.log(order_id);
      var that = this;
      util.getAjax(`${app.globalData.apiUrl}/user_yes_service_shop_order`,(res)=>{
          console.log(res);
          if(res.data == 1){
              util.showToast('确认已收货','success',1000);
              that.getData();
          }
      },{
          order_id:order_id
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      let that = this;
      if(app.globalData.userId){
          that.setData({
              userId: app.globalData.userId
          })
          that.getData()
      }else{
          app.userIdCallback = userId => {
              if (userId != '') {
                  that.setData({
                      userId: userId
                  });
                  that.getData()
              }
          }
      }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.isFail){
      this.getData()
      return
    }
    loadMoreView.loadMore()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
